package com.citicup.backend.webmagic;

import com.citicup.backend.dao.FundDailyMapper;
import com.citicup.backend.dao.FundInfoMapper;
import com.citicup.backend.dao.StockDailyMapper;
import com.citicup.backend.entity.FundDaily;
import com.citicup.backend.entity.FundInfo;
import com.citicup.backend.entity.StockDaily;
import com.citicup.backend.util.UpdateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.List;

@Component
@Slf4j
public class MysqlPipeline implements Pipeline {

    private final FundInfoMapper fundInfoMapper;

    private final StockDailyMapper stockDailyMapper;

    private final FundDailyMapper fundDailyMapper;

    @Autowired
    public MysqlPipeline(FundInfoMapper fundInfoMapper, StockDailyMapper stockDailyMapper, FundDailyMapper fundDailyMapper) {
        this.fundInfoMapper = fundInfoMapper;
        this.stockDailyMapper = stockDailyMapper;
        this.fundDailyMapper = fundDailyMapper;
    }

    @Override
    public void process(ResultItems resultItems, Task task) {
        synchronized (MysqlPipeline.class) {
            FundInfo fundInfo = resultItems.get("FundInfo");
            if (fundInfo != null) {
                List<FundInfo> pastInfo = fundInfoMapper.findByFundCode(fundInfo.getFundCode());
                if (pastInfo.size() >= 1) {
                    FundInfo pastFund = pastInfo.get(0);
                    UpdateUtil.copyNullProperties(pastFund, fundInfo);
                    fundInfo.setId(pastFund.getId());
                    if (pastFund.getFundScale() != 0)
                        fundInfo.setFundScale(pastFund.getFundScale());
                }
                fundInfoMapper.save(fundInfo);
            }
        }
        StockDaily stockDaily = resultItems.get("StockDaily");
        if (stockDaily != null) {
            stockDailyMapper.save(stockDaily);
        }
        FundDaily fundDaily = resultItems.get("FundDaily");
        if (fundDaily != null) {
            fundDailyMapper.save(fundDaily);
        }
        List<FundDaily> fundDailies = resultItems.get("historyFund");
        if (fundDailies != null && fundDailies.size() != 0) {
            for(FundDaily each:fundDailies)
                fundDailyMapper.save(each);
        }
    }
}
